import { delay, postMsg, buildMsgHandler, postFilters } from '../utils.js';
import { fillTable as fillCwbb } from './cwbb.js';
import { fillTable as fillHsqj } from './hsqj.js';
import { isFillYearBeforeLast } from '../common.js';

let baseInfoCache;

async function doLogin({ companyInfo }) {
  await delay(1000);
  window.layer.closeAll();
  await delay(500);

  document.querySelector('#login').click();

  const { nationalTaxAccount, nationalTaxId, nationalTaxPass, taxStaffPhone } =
    companyInfo || {};

  $('#sm_username').val(nationalTaxAccount || nationalTaxId);
  $('#smPassword').val(nationalTaxPass);
  $('#sm_phone').val(taxStaffPhone);
}

function postKjzd() {
  try {
    let institutionCode = '';
    const clientName = document.querySelector("#cwbbbgbsTable > tbody > tr:nth-child(1) > td:nth-child(2)").innerText;
    // const clientName = document.querySelector(
    //   '.layui-layer.layui-layer-iframe .layui-layer-title'
    // ).innerText;


    // if (!clientName.includes('财务报表年报')) {
    //   throw new Error('不支持的财务报表');
    // }

    if (clientName.includes('小企业')) {
      institutionCode = 2;
    } else if (clientName.includes('企业')) {
      institutionCode = 1;
    }

    postMsg('fixTaxGovInfo', { institutionCode });
  } catch (e) {
    console.error(e)
  }
}

async function doSaasData(baseInfo, data) {
  switch (data.saasData.sheetType) {
    case 'hsqj-gener':
    case 'hsqj-small':
      await fillHsqj(data.saasData.data);
      break;
    case 'cwbb':
      const shouldFillLastYear = isFillYearBeforeLast(baseInfo);
      await fillCwbb(
        data.saasData.data.openParams.inputData,
        shouldFillLastYear,
        data.saasData
      );
      break;
    default:
      break;
  }
}

$(window).ready(function () {
  postMsg('getBaseInfo');

  const msgHandler = buildMsgHandler({
    baseInfo: baseInfoCache,
    loginURLExp: /\/cas\/login/,
    onBaseInfo: doLogin,
    onSaasData: doSaasData,
  });
  window.addEventListener('message', msgHandler, false);
});
